package com.yunxi.service.localService.impl.sto;

import com.alibaba.cloud.context.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunxi.bizToHub.pojo.VehicleStockShiftVO;
import com.yunxi.bizToHub.service.VehicleStockManageDubboService;
import com.yunxi.core.service.ServiceImplPlus;
import com.yunxi.core.web.DictConstant;
import com.yunxi.dao.sto.StoChangeStorageMapper;
import com.yunxi.dealer.pojo.PartnerVO;
import com.yunxi.model.order.PmsVehicleStock;
import com.yunxi.model.sto.StoChangeStorage;
import com.yunxi.model.sto.StoManage;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.service.localService.sto.StoChangeStorageService;
import com.yunxi.service.localService.sto.StoManageService;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.service.localService.sto.VehicleStockMService;
import com.yunxi.sto.pojo.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 车辆移库单 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-05-28
 */
@Service
public class StoChangeStorageServiceImpl extends ServiceImplPlus<StoChangeStorageMapper, StoChangeStorage> implements StoChangeStorageService {

    @Autowired
    @Qualifier(value = "stoManageServiceImpl")
    StoManageService stoManageService;

    @Autowired
    @Qualifier(value = "vehicleStockMServiceImpl")
    VehicleStockMService vehicleStockMService;

    @Autowired
    @Qualifier(value = "vehicleStockManageDubboServiceImplBiz")
    VehicleStockManageDubboService vehicleStockManageDubboService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    private static final Logger logger = LoggerFactory.getLogger(StoChangeStorageServiceImpl.class);

    /**
     * 获取渠道商在库车辆列表
     * @return
     */
    @Override
    public List vinList(PartnerVO vo) {
        return baseMapper.vinList(vo);
    }

    @Override
    public List storageList(VehiclePdiBillVO vehiclePdiBillVO) {
        //渠道商代码
        return baseMapper.storageList(vehiclePdiBillVO);
    }

    /**
     * 作废/恢复
     * @param list
     */
    @Override
    public void delByList(List<String> list,String billState,String userId)throws Exception {
        if (list != null && list.size() > 0) {
            for (String id : list) {
                //只能作废新建的移库单
                StoChangeStorage stoChangeStorage = baseMapper.selectById(id);
                if (stoChangeStorage != null) {
                    String oldBillState = stoChangeStorage.getBillState();
                    String newStorageCode = stoChangeStorage.getNewStorageCode();
                    if(billState.equals("3") && !oldBillState.equals("0")){
                        throw new Exception("操作失败,只能作废新建的单据!");
                    }
                    else if(billState.equals("0") && !oldBillState.equals("3")){
                        throw new Exception("操作失败,只能恢复作废的单据!");
                    }
                    //恢复之前,检验该VIN码是否存在未完成的移库单
                    if(billState.equals("0")){
                        String vin = stoChangeStorage.getVin();
                        QueryWrapper<StoChangeStorage> queryWrapper = new QueryWrapper<>();
                        queryWrapper.eq("VIN",vin);
                        queryWrapper.ne("BILL_STATE","2");
                        queryWrapper.ne("BILL_STATE","3");
                        List<StoChangeStorage> list2 = baseMapper.selectList(queryWrapper);
                        if(list2 != null && list2.size() > 0){
                            throw new Exception("操作失败,VIN码:"+vin+"已存在新建或者移库中的单据!");
                        }
                        //恢复目标库位冻结状态为解冻,同时判断该库位未冻结,未占用,未作废才能恢复成功
                        QueryWrapper<StoManage> objectQueryWrapper = new QueryWrapper<>();
                        objectQueryWrapper.eq("STORAGE_CODE",newStorageCode);
                        StoManage one = stoManageService.getOne(objectQueryWrapper);
                        if(one != null){
                            Integer isPositionDisabled = one.getIsPositionDisabled();
                            Integer isPositionFrozen = one.getIsPositionFrozen();
                            String storagePositionState = one.getStoragePositionState();
                            if((isPositionDisabled != null && isPositionDisabled.equals(1))
                                    ||(isPositionFrozen != null && isPositionFrozen.equals(1))
                                    || (storagePositionState != null && storagePositionState.equals("2"))){
                                //方案一,清空该移库单的目标库位,成功恢复
                                stoChangeStorage.setNewStorageCode(null);
                                //方案二,报错提示该库位不可用
//                                throw new Exception("操作失败,库位"+one.getStorageFullName()+"不可用,无法恢复该移库单!");
                            }
                            //冻结目标库位
                            unFrozenStorageCode(newStorageCode,1);
                        }
                    }
                    //作废,同时解冻占用的库位
                    else if(billState.equals("3")){
                        //解冻目标库位
                        unFrozenStorageCode(newStorageCode,0);
                    }
                    stoChangeStorage.setBillState(billState);
                    stoChangeStorage.setUpdateBy(userId);
                    baseMapper.updateById(stoChangeStorage);
                }
                else{
                    throw new Exception("操作失败,无法根据主键id:"+id+"找到对应单据!");
                }
            }
        }
        else {
            throw new Exception("操作失败,list为空!");
        }
    }

    /**
     * 解冻目标库位
     * @param newStorageCode
     */
    private StoManage unFrozenStorageCode(String newStorageCode,Integer isFrozen) {
        QueryWrapper<StoManage> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("STORAGE_CODE",newStorageCode);
        StoManage stoManage = stoManageService.getOne(objectQueryWrapper);
        if(stoManage != null){
            stoManage.setIsPositionFrozen(isFrozen);
            stoManageService.updateById(stoManage);

            vehicleStockMService.newFrozenHis(isFrozen.toString(),null,newStorageCode,1);
        }
        else{
            stoManage = new StoManage();
        }
        return stoManage;
    }

    /**
     * 移库扫码获取车辆信息
     * @param vin
     * @return
     */
    @Override
    public StoChangeStorageVehicleInfoVO pdaVehicleInfo(String vin) throws Exception{
        StoChangeStorageVehicleInfoVO vo = baseMapper.pdaVehicleInfo(vin);
        if(vo == null || vo.getVin() == null){
//            throw new Exception("操作失败,无法根据VIN码:"+vin+"找到对应车辆信息!");
        }
        /*String ck = vo.getStorageName();//仓库名
        String kq = vo.getKq();//库区名
        String kd = vo.getKd();//库道名
        String kw = vo.getStorageLocationName();//库位
        if(StringUtil.isNotEmpty(ck) && StringUtil.isNotEmpty(kq) && StringUtil.isNotEmpty(kd) && StringUtil.isNotEmpty(kw)){
            vo.setStorageFullName(ck+"-"+kq+"-"+kd+"-"+kw);
        }*/
        return vo;
    }

    /**
     * 开始移库
     * @param stoStockScanVO
     */
    @Override
    public void startChange(StoStockScanVO stoStockScanVO)throws Exception {
        String vin = stoStockScanVO.getVin();
        String rfidNo = stoStockScanVO.getRfidNo();
        //1.更新移库单状态为移库中
        QueryWrapper<StoChangeStorage> queryWrapper = new QueryWrapper();
        queryWrapper.eq("VIN",vin);
        queryWrapper.eq("BILL_STATE","0");
        StoChangeStorage stoChangeStorage = baseMapper.selectOne(queryWrapper);
        if(stoChangeStorage != null){
            stoChangeStorage.setBillState("1");
            stoChangeStorage.setRfidNo(rfidNo);
            baseMapper.updateById(stoChangeStorage);
        }
        else{
            throw new Exception("操作失败,无法根据VIN码:"+vin+"找到对应移库计划!");
        }
    }

    /**
     * 校验VIN是否存在未完成的移库单
     * @param stoChangeStorageEditVO
     * @return
     */
    @Override
    public Boolean queryIsExsit(StoChangeStorageEditVO stoChangeStorageEditVO) {
        Boolean isExsit = false;
        QueryWrapper<StoChangeStorage> queryWrapper = new QueryWrapper();
        queryWrapper.eq("VIN",stoChangeStorageEditVO.getVin());
        queryWrapper.ne("BILL_STATE","2");
        queryWrapper.ne("BILL_STATE","3");
        if(stoChangeStorageEditVO.getChangeStorageId() != null){
            queryWrapper.ne("CHANGE_STORAGE_ID",stoChangeStorageEditVO.getChangeStorageId());
        }
        StoChangeStorage stoChangeStorage = baseMapper.selectOne(queryWrapper);
        if(stoChangeStorage != null){
            isExsit = true;
        }
        return isExsit;
    }

    /**
     * 完成移库
     * @param stoStockScanVO
     */
    @Override
    public void complete(StoStockScanVO stoStockScanVO) throws Exception {
        QueryWrapper<StoChangeStorage> queryWrapper = new QueryWrapper();
        queryWrapper.eq("VIN",stoStockScanVO.getVin());
        queryWrapper.eq("BILL_STATE","1");
        StoChangeStorage stoChangeStorage = baseMapper.selectOne(queryWrapper);
        if(stoChangeStorage != null){
            //1.更新移库单据状态
            stoChangeStorage.setBillState("2");
            stoChangeStorage.setCompleteTime(new Date());
            stoChangeStorage.setRfidNo(stoStockScanVO.getRfidNo());
            //更新所属仓库名
            String storageFullName = stoManageService.getStorageFullName(stoChangeStorage.getNewStorageCode());
            if(StringUtils.isNotEmpty(storageFullName)){
                String[] split = storageFullName.split("-");
                stoChangeStorage.setStorageName(split[0]);
            }
            baseMapper.updateById(stoChangeStorage);

            //2.解冻新库位,更新使用状态为占用,更新老库位使用状态为空闲
            String newStorageCode = stoChangeStorage.getNewStorageCode();
            QueryWrapper<StoManage> queryWrapper1 = new QueryWrapper();
            StoManage stoManage = unFrozenStorageCode(newStorageCode,0);
            stoManage.setStoragePositionState("2");
            stoManageService.updateById(stoManage);
            String oldStorageCode = stoChangeStorage.getOldStorageCode();
            QueryWrapper<StoManage> queryWrapper2 = new QueryWrapper();
            queryWrapper2.eq("STORAGE_CODE",oldStorageCode);
            StoManage stoManage1 = stoManageService.getOne(queryWrapper2);
            if(stoManage1 != null){
                stoManage1.setStoragePositionState("1");
                stoManageService.updateById(stoManage1);
            }

            //3.更新 pms_vehicle_stock 库位代码
            QueryWrapper<PmsVehicleStock> queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("VIN",stoStockScanVO.getVin());
            PmsVehicleStock vehicleStock = vehicleStockMService.getOne(queryWrapper3);
            if(vehicleStock != null){
                vehicleStock.setStorageLocation(stoChangeStorage.getNewStorageCode());
                vehicleStock.setVehicleIsFrozen("0");
                vehicleStockMService.updateById(vehicleStock);
            }

            //解锁车辆
            QueryWrapper<VehicleOffline> queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.eq("VIN",stoStockScanVO.getVin());
            VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper4);
            if(vehicleOffline != null){
                vehicleOffline.setVehicleIsFrozen(0);
                vehicleOfflineService.saveOrUpdate(vehicleOffline);
            }
            VehicleStockFrozenVO vehicleStockFrozenVO = new VehicleStockFrozenVO();
            //新增冻结解冻历史
            vehicleStockFrozenVO.setFrozenReason("车辆移库");
            vehicleStockMService.newFrozenHis("0",vehicleStockFrozenVO,stoStockScanVO.getVin(),2);

            //4.整车库存同步接口,PMS推送到SAP
            VehicleStockShiftVO vehicleStockShiftVO1 = new VehicleStockShiftVO();
            List<VehicleStockShiftVO> vehicleStockShiftVO = baseMapper.queryStockChangeInfo(stoStockScanVO.getVin());
            if(vehicleStockShiftVO != null && vehicleStockShiftVO.size() > 0){
                vehicleStockShiftVO1 = vehicleStockShiftVO.get(0);
                vehicleStockShiftVO1.setSeqno(stoChangeStorage.getChangeStorageNo());
                vehicleStockShiftVO1.setBwart(DictConstant.VEHICLE_STATE_MOVE_IN);
                vehicleStockManageDubboService.vehicleStockShiftPms2Sap(vehicleStockShiftVO1);
            }
            else {
                logger.debug("操作失败,整车库存同步接口推送消息为空!");
                throw new Exception("操作失败,整车库存同步接口推送消息为空!");
            }
        }
    }

    @Override
    public List<VehicleStockShiftVO> queryStockChangeInfo(String vin) {
        return baseMapper.queryStockChangeInfo(vin);
    }

    /**
     * 根据VIN查询移库计划
     * @param vin
     * @return
     * @throws Exception
     */
    @Override
    public List<StoChangeStorageVO> planListByVin(String vin) throws Exception {
        return baseMapper.planListByVin(vin);
    }

    @Override
    public StoChangeStorageVO getInfoById(String id) throws Exception {
        return baseMapper.getInfoById(id);
    }

    /**
     * 导出
     * @param stoChangeStorageQueryVO
     * @return
     */
    @Override
    public List<StoChangeStorageExportVO> exportList(StoChangeStorageQueryVO stoChangeStorageQueryVO) {
        return baseMapper.exportList(stoChangeStorageQueryVO);
    }
}
